﻿using CBApp.DataModels;
using CBApp.Db.IDataAdapters.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CBApp.Db.IDataAdapters.Adapters
{
    public class CBAdapter : ICBAdapter
    {
        public ComicBook AddComicBook(ComicBook comicbook)
        {
            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                comicbook = db.ComicBooks.Add(comicbook);
                db.SaveChanges();
            }
            return comicbook;
        }

        public List<ComicBook> GetAllComicBooks()
        {
            List<ComicBook> comicbooks;
            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                comicbooks = db.ComicBooks.OrderBy(x => x.Title).ToList();
            }
            return comicbooks;
        }

        public ComicBook GetComicBook(int id)
        {
            ComicBook comicbook;
            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                comicbook = db.ComicBooks.Include("Characters").Where(x => x.Id == id).FirstOrDefault();
            }
            return comicbook;
        }

        public ComicBook UpdateComicBook(ComicBook comicbook)
        {
            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                ComicBook oldcb = db.ComicBooks.Find(comicbook.Id);
                oldcb.setProps(comicbook);
                db.SaveChanges();
            }
            return comicbook;
        }

        public void DeleteComicBook(int id)
        {
            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                ComicBook comicbook = db.ComicBooks.Find(id);
                db.ComicBooks.Remove(comicbook);
                db.SaveChanges();
            }
        }

        public List<Artist> GetArtistsForComicBook(int comicbookId)
        {
            List<Artist> artists = new List<Artist>();
            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                List<ArtistComicBook> acb = db.ArtistComicBooks.Where(x => x.ComicBookId == comicbookId).ToList();
                foreach (var ac in acb)
                {
                    artists.Add(db.Artists.Where(x => x.Id == ac.ArtistId).FirstOrDefault());
                }
                return artists;
            }
        }
    }
}
